package server;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;
import java.util.Timer;
import java.util.TimerTask;


/**
 * The Class ServerController.
 * Validates the MySql connection details typed by user. 
 * if correct , creates an instance of SGIserverV1 and a connection to MySql server.
 * @author Tomer Elakaym 
 */
public class ServerController 
{
	/** The db info window in this window the user enters the database connection details. */
	private ServerGUI dbInfoWindow;
	
	/** The db handler. */
	private DBcomunicator dbHandler;
	
	/**
	 * Instantiates a new server controller.
	 *
	 * @param dbInfoWindow the db info window
	 * @param dbHandler the db handler
	 */
	public ServerController(ServerGUI dbInfoWindow,DBcomunicator dbHandler )
	{
		this.dbHandler = dbHandler;
		this.dbInfoWindow = dbInfoWindow;
		this.dbInfoWindow.addContinueListener(new ContinueListener());
		this.dbInfoWindow.addCancleListener(new CancelListener());
	}
	
	/**
	 * The inner class that listen for continue button press events.
	 * The object created with this class is registered with a component using the
	 * component's <code>addContinueListener<code> method. 
	 * Whenthe continue event occurs , the details the user typed are being evaluated.
	 * on success, the server is up and running.
	 */
	class ContinueListener implements ActionListener
	{
		
		/* (non-Javadoc)
		 * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
		 */
		@Override
		public void actionPerformed(ActionEvent arg0) 
		{
			String scheme,password,username;
			//get information
			scheme = dbInfoWindow.getSchemeField(); //scheme the DB name. received from GUI.
			password = dbInfoWindow.getPasswordField(); //password the MySql password. received from GUI.
			username = dbInfoWindow.getUsernameField();// username the MySql username. received from GUI.
			if(scheme==null || password == null || username == null )
			{
				dbInfoWindow.clearAllFields();
				dbInfoWindow.displayErrorMessage("one or more fields are not filled");
			}
			else
			{
				boolean isConnected = dbHandler.connectToDB(scheme ,username ,password );
				if(isConnected == false)
				{
					dbInfoWindow.clearAllFields();
					dbInfoWindow.displayErrorMessage("Connection to DB Faild! try again");
				}
				else
				{
					int port; // port number to listen on. received from GUI.
				
					try
					{
						port = Integer.parseInt(dbInfoWindow.getPortField());
					}
					catch(Throwable t)
					{
						port = SGIServerV1.DEFAULT_PORT; //Set port to 5555
					}
					
					
					
					Timer DailyTimer = new Timer ();
					TimerTask DailyTask = new TimerTask () {
					    @Override
					    public void run () {
					    	ServerProduceReport report = new ServerProduceReport(dbInfoWindow.getSchemeField(), dbInfoWindow.getUsernameField(), dbInfoWindow.getPasswordField());
					    	try {
								report.dailyStatistic();
							} catch (SQLException e) {
								e.printStackTrace();
							}
					    }
					};
					
					DailyTimer.schedule (DailyTask, 100, 1000*60*60*24);
					
					Timer WeeklyTimer = new Timer ();
					TimerTask WeeklyTask = new TimerTask () {
					    @Override
					    public void run () {
					    	ServerProduceReport report = new ServerProduceReport(dbInfoWindow.getSchemeField(), dbInfoWindow.getUsernameField(), dbInfoWindow.getPasswordField());
					    	try {
					    		System.out.println ("Weekly Report ON");
								report.weeklyStatistic();
							} catch (SQLException e) {
								e.printStackTrace();
							}
					    }
					};
					
					WeeklyTimer.schedule (WeeklyTask, 100, 1000*60*60*24*7);
					
					Timer YearlyTimer = new Timer ();
					TimerTask YearlyTask = new TimerTask () {
					    @Override
					    public void run () {
					    	ServerProduceReport report = new ServerProduceReport(dbInfoWindow.getSchemeField(), dbInfoWindow.getUsernameField(), dbInfoWindow.getPasswordField());
					    	try {
								report.yearlyStatistic();
							} catch (SQLException e) {
								e.printStackTrace();
							}
					    }
					};
					

					YearlyTimer.schedule (YearlyTask, 100, 1000*60*60*24*365);
					 
					//create a new server instance
					SGIServerV1 sgiServer = new SGIServerV1(port);
			    
					try 
					{
						sgiServer.listen(); //Start listening for connections
						dbInfoWindow.setVisible(false); //close the window and keep server running on background
					
						//set observer
						sgiServer.addObserver(dbHandler);
					
						//start listening
						if(sgiServer.isListening())
							System.out.println("Server is listening to port:"+ port);
					} 
					catch (Exception ex) 
					{
						dbInfoWindow.displayErrorMessage("Error:" + ex.getMessage());
					}
				}
			}				
		}
	}
	
	/**
	 * The inner class that listens for receiving cancel button press events.
	 * The object created with this class is registered with a component using the
	 * component's <code>addCancelListener<code> method. When
	 * the cancel event occurs, the window is disposed and the program ends.
	 *
	 * @see CancelEvent
	 */
	class CancelListener implements ActionListener
	{
		
		/* (non-Javadoc)
		 * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
		 */
		@Override
		public void actionPerformed(ActionEvent arg0) 
		{
			dbInfoWindow.setVisible(false);
			System.exit(0);
		}
		
	}
	
}
